package com.semac.client.componentes.atividadestable;

import com.google.gwt.cell.client.ActionCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.semac.shared.model.Atividade;

public class InscricaoActionCell extends ActionCell<Atividade> {

	public InscricaoActionCell(Delegate<Atividade> delegate) {
		super("", delegate);
	}
	
	private final SafeHtml buttonSafeHTML = new SafeHtmlBuilder()
												.appendHtmlConstant("<button type=\"button\" tabindex=\"-1\">" +
																	"Adicionar à minha lista" +
																	"</button>")
												.toSafeHtml();
    
	private final SafeHtml noButton = new SafeHtmlBuilder()
												.appendHtmlConstant("<div>Não tem inscrição</div>")
												.toSafeHtml();
	
	
	
	@Override
	public void onBrowserEvent(Context context, Element parent, Atividade value, NativeEvent event, ValueUpdater<Atividade> valueUpdater) {
		if ("click".equals(event.getType())) {
			EventTarget eventTarget = event.getEventTarget();
			if (!Element.is(eventTarget)) {
				return;
			}
			if (parent.getFirstChildElement().isOrHasChild(Element.as(eventTarget))) {
				// Ignore clicks that occur outside of the main element.
				onEnterKeyDown(context, parent, value, event, valueUpdater);
			}
		}
	}

	protected void onEnterKeyDown(Context context, Element parent, Atividade value, NativeEvent event, ValueUpdater<Atividade> valueUpdater) {
		if (value.isTemInscricao())
			super.onEnterKeyDown(context, parent, value, event, valueUpdater);
	};
	

	public void render(Context context, Atividade value, SafeHtmlBuilder sb) {
    	if ((value != null) && value.isTemInscricao())
    		sb.append(buttonSafeHTML);
    	else
    		sb.append(noButton);
	}
}
